package com.learn.oss.controller;

import com.google.common.collect.Maps;
import com.learn.oss.constant.Constans;
import com.mate.cloud.common.response.BaseResponse;
import com.mate.cloud.common.web.controller.AdminBaseController;
import com.mate.cloud.core.util.StringPool;
import com.mate.cloud.oss.props.OssProperties;
import com.mate.cloud.oss.service.OssTemplate;
import jakarta.annotation.Resource;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * OssController类，用于进行接口测试
 * @author: Administrator
 * @createTime: 2023/12/13 0013 16:42
 * @version: 1.0
 */
@RestController
@RequestMapping("/oss")
public class OssController extends AdminBaseController {


    @Resource
    private OssTemplate ossTemplate;


    @PostMapping("/upload")
    public BaseResponse upload(@RequestParam(value = "files") MultipartFile files) throws IOException {
        Map<String, String> uMap = Maps.newHashMap();
        OssProperties ossProperties = new OssProperties();

        String fileName = UUID.randomUUID().toString().replace("-", "")
                + StringPool.DOT + FilenameUtils.getExtension(files.getOriginalFilename());
        ossTemplate.putObject(Constans.BUCKET_NAME,fileName,files.getInputStream());
        String url = "https://" + ossProperties.getEndpoint() + StringPool.SLASH + fileName;
        uMap.put("bucketName", ossProperties.getBucketName());
        uMap.put("fileName", fileName);
        uMap.put("url", url);
        return successBodyResponse(uMap);
    }

    /**
     * 获取文件URL
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @return
     * @throws IOException
     */
    @GetMapping("/url")
    public BaseResponse url(@RequestParam(value = "bucketName") String bucketName,String objectName) throws IOException {


        String objectURL = ossTemplate.getObjectURL(Constans.BUCKET_NAME, objectName);

        return successBodyResponse(objectURL);
    }
}
